<template>
  <div class="goods-container">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards" v-loading="loading.stats">
      <el-col :span="6" v-for="(item, index) in statsData" :key="index">
        <el-card shadow="hover" class="stats-card" :body-style="{ padding: '20px' }">
          <div class="stats-card-header">
            <span class="stats-card-title">{{ item.title }}</span>
            <el-tooltip :content="item.tooltip" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="stats-card-content">
            <span class="stats-card-value">{{ item.value }}</span>
            <span class="stats-card-unit">{{ item.unit }}</span>
            <el-tag :type="item.trend >= 0 ? 'success' : 'danger'" size="small" class="trend-tag">
              {{ item.trend >= 0 ? '+' : '' }}{{ item.trend }}%
            </el-tag>
          </div>
          <div class="stats-card-chart">
            <div ref="trendChartRefs" :id="'trendChart' + index" class="trend-chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作栏 -->
    <div class="quick-actions">
      <el-button-group>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建商品
        </el-button>
        <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </el-button-group>
      <el-button-group>
        <el-button
          v-for="action in quickActions"
          :key="action.value"
          :type="action.type"
          @click="handleQuickAction(action.value)"
        >
          <el-icon><component :is="action.icon" /></el-icon>
          {{ action.label }}
        </el-button>
      </el-button-group>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="商品名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="filterForm.categoryIds"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            clearable
            placeholder="请选择商品分类"
          />
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="(label, value) in GOODS_TYPE"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="(label, value) in GOODS_STATUS"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input-number
            v-model="filterForm.minPrice"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="最低价"
          />
          <span class="separator">-</span>
          <el-input-number
            v-model="filterForm.maxPrice"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="最高价"
          />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="list-card" shadow="never" v-loading="loading.list">
      <template #header>
        <div class="list-header">
          <div class="left">
            <el-radio-group v-model="listView" size="small">
              <el-radio-button label="table">表格视图</el-radio-button>
              <el-radio-button label="card">卡片视图</el-radio-button>
            </el-radio-group>
            <el-tag type="info" class="ml-2">已选择 {{ selectedGoods.length }} 项</el-tag>
          </div>
          <div class="right">
            <el-button-group>
              <el-button
                v-for="action in batchActions"
                :key="action.value"
                :type="action.type"
                :disabled="!selectedGoods.length"
                @click="handleBatchAction(action.value)"
              >
                {{ action.label }}
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
        <el-table
        v-if="listView === 'table'"
          :data="goodsList"
        style="width: 100%"
          @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品信息" min-width="400">
            <template #default="scope">
            <div class="goods-info">
              <el-image
                :src="scope.row.mainImage"
                :preview-src-list="[scope.row.mainImage]"
                fit="cover"
                class="goods-image"
              />
              <div class="goods-detail">
                <div class="goods-name">
                  <el-tag :type="getGoodsTypeTag(scope.row.type)" size="small">
                    {{ getGoodsTypeLabel(scope.row.type) }}
                  </el-tag>
                  <span>{{ scope.row.name }}</span>
                  </div>
                <div class="goods-sku">
                  <span v-if="scope.row.specType === SPEC_TYPE.MULTI">
                    {{ scope.row.specCount }}个规格
                  </span>
                  <span v-else>单规格</span>
                  <span class="separator">|</span>
                  <span>库存: {{ scope.row.stock }}</span>
                  <span class="separator">|</span>
                  <span>销量: {{ scope.row.sales }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="scope">
            <div class="price-info">
              <div class="current-price">¥{{ scope.row.price }}</div>
              <div class="original-price" v-if="scope.row.originalPrice">
                ¥{{ scope.row.originalPrice }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
            </template>
          </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
            <el-button-group>
              <el-button
                v-if="scope.row.status === GOODS_STATUS.APPROVED"
                type="success"
                link
                @click="handleStatusChange(scope.row, GOODS_STATUS.ON_SALE)"
              >
                上架
              </el-button>
              <el-button
                v-if="scope.row.status === GOODS_STATUS.ON_SALE"
                type="warning"
                link
                @click="handleStatusChange(scope.row, GOODS_STATUS.OFF_SALE)"
              >
                下架
              </el-button>
              <el-button
                v-if="[GOODS_STATUS.DRAFT, GOODS_STATUS.REJECTED].includes(scope.row.status)"
                type="primary"
                link
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="[GOODS_STATUS.DRAFT, GOODS_STATUS.REJECTED].includes(scope.row.status)"
                type="danger"
                link
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
            </template>
          </el-table-column>
        </el-table>

      <!-- 卡片视图 -->
      <div v-else class="goods-grid">
        <el-card
          v-for="item in goodsList"
          :key="item.id"
          class="goods-card"
          shadow="hover"
          :body-style="{ padding: '0' }"
        >
          <div class="goods-card-header">
            <el-checkbox
              v-model="item.selected"
              @change="(val) => handleCardSelect(item, val)"
            />
            <el-dropdown trigger="click" @command="(cmd) => handleCardAction(item, cmd)">
              <el-button type="primary" link>
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="item.status === GOODS_STATUS.APPROVED"
                    command="on_sale"
                  >
                    上架
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="item.status === GOODS_STATUS.ON_SALE"
                    command="off_sale"
                  >
                    下架
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="[GOODS_STATUS.DRAFT, GOODS_STATUS.REJECTED].includes(item.status)"
                    command="edit"
                  >
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="[GOODS_STATUS.DRAFT, GOODS_STATUS.REJECTED].includes(item.status)"
                    command="delete"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="goods-card-content" @click="handlePreview(item)">
            <el-image
              :src="item.mainImage"
              :preview-src-list="[item.mainImage]"
              fit="cover"
              class="goods-card-image"
            />
            <div class="goods-card-info">
              <div class="goods-card-name">
                <el-tag :type="getGoodsTypeTag(item.type)" size="small">
                  {{ getGoodsTypeLabel(item.type) }}
                </el-tag>
                <span>{{ item.name }}</span>
              </div>
              <div class="goods-card-price">
                <span class="current-price">¥{{ item.price }}</span>
                <span class="original-price" v-if="item.originalPrice">
                  ¥{{ item.originalPrice }}
                </span>
              </div>
              <div class="goods-card-meta">
                <span>{{ item.categoryName }}</span>
                <span class="separator">|</span>
                <span>库存: {{ item.stock }}</span>
                <span class="separator">|</span>
                <span>销量: {{ item.sales }}</span>
              </div>
              <div class="goods-card-status">
                <el-tag :type="getStatusType(item.status)" size="small">
                  {{ getStatusLabel(item.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination">
          <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
            :total="total"
          layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="商品预览"
      width="800px"
      destroy-on-close
      class="preview-dialog"
    >
      <div class="preview-content" v-loading="loading.preview">
        <div class="preview-header">
          <el-image
            :src="previewData.mainImage"
            :preview-src-list="previewData.images"
            fit="cover"
            class="preview-image"
          />
          <div class="preview-info">
            <h2 class="preview-title">{{ previewData.name }}</h2>
            <div class="preview-meta">
              <el-tag :type="getGoodsTypeTag(previewData.type)" size="small">
                {{ getGoodsTypeLabel(previewData.type) }}
              </el-tag>
              <el-tag :type="getStatusType(previewData.status)" size="small">
                {{ getStatusLabel(previewData.status) }}
              </el-tag>
            </div>
            <div class="preview-price">
              <span class="current-price">¥{{ previewData.price }}</span>
              <span class="original-price" v-if="previewData.originalPrice">
                ¥{{ previewData.originalPrice }}
              </span>
            </div>
            <div class="preview-stats">
              <div class="stat-item">
                <span class="label">库存</span>
                <span class="value">{{ previewData.stock }}</span>
              </div>
              <div class="stat-item">
                <span class="label">销量</span>
                <span class="value">{{ previewData.sales }}</span>
              </div>
              <div class="stat-item">
                <span class="label">浏览量</span>
                <span class="value">{{ previewData.views }}</span>
              </div>
            </div>
          </div>
        </div>
        <el-tabs v-model="previewTab">
          <el-tab-pane label="商品详情" name="detail">
            <div class="preview-detail" v-html="previewData.detail"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="specs">
            <el-descriptions :column="2" border>
              <el-descriptions-item
                v-for="spec in previewData.specs"
                :key="spec.name"
                :label="spec.name"
              >
                {{ spec.value }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="销售记录" name="sales">
            <el-table :data="previewData.salesRecords" style="width: 100%">
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column prop="spec" label="规格" />
              <el-table-column prop="quantity" label="数量" width="100" />
              <el-table-column prop="price" label="单价" width="120" />
              <el-table-column prop="total" label="总价" width="120" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="评价记录" name="reviews">
            <div class="review-list">
              <div
                v-for="review in previewData.reviews"
                :key="review.id"
                class="review-item"
              >
                <div class="review-header">
                  <el-avatar :src="review.userAvatar" :size="32" />
                  <div class="review-user">
                    <div class="username">{{ review.username }}</div>
                    <div class="time">{{ review.time }}</div>
                  </div>
                  <el-rate v-model="review.rating" disabled />
                </div>
                <div class="review-content">{{ review.content }}</div>
                <div class="review-images" v-if="review.images?.length">
                  <el-image
                    v-for="img in review.images"
                    :key="img"
                    :src="img"
                    :preview-src-list="review.images"
                    fit="cover"
                    class="review-image"
                  />
                </div>
                <div class="review-reply" v-if="review.reply">
                  <div class="reply-header">商家回复：</div>
                  <div class="reply-content">{{ review.reply }}</div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入商品"
      width="500px"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/merchant/goods/import"
        :headers="uploadHeaders"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        :before-upload="beforeImport"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<el-link type="primary" @click="downloadTemplate">点击上传</el-link>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传 Excel 文件，<el-link type="primary" @click="downloadTemplate">下载模板</el-link>
        </div>
      </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Upload,
  UploadFilled,
  QuestionFilled,
  ArrowDown,
  Document,
  List,
  TrendCharts,
  Setting
} from '@element-plus/icons-vue'
import {
  GOODS_STATUS,
  GOODS_TYPE,
  SPEC_TYPE,
  getGoodsList,
  getGoodsDetail,
  getGoodsStats,
  getGoodsSalesTrend,
  getGoodsCategorySales,
  getHotGoods,
  getGoodsReviews,
  updateGoodsStatus,
  batchUpdateGoodsStatus,
  deleteGoods,
  batchDeleteGoods,
  importGoods,
  exportGoods
} from '@/api/goods'
import * as echarts from 'echarts'

// 统计数据
const loading = reactive({
  stats: false,
  list: false,
  preview: false,
  submit: false
})

const statsData = ref([
  {
    title: '商品总数',
    value: 0,
    unit: '个',
    trend: 0,
    tooltip: '店铺所有商品数量',
    type: 'primary'
  },
  {
    title: '在售商品',
    value: 0,
    unit: '个',
    trend: 0,
    tooltip: '当前在售商品数量',
    type: 'success'
  },
  {
    title: '本月销量',
    value: 0,
    unit: '件',
    trend: 0,
    tooltip: '本月商品销售总量',
    type: 'warning'
  },
  {
    title: '本月销售额',
    value: 0,
    unit: '元',
    trend: 0,
    tooltip: '本月商品销售总额',
    type: 'danger'
  }
])

// 筛选表单
const filterForm = reactive({
  name: '',
  categoryIds: [],
  type: '',
  status: '',
  minPrice: null,
  maxPrice: null,
  dateRange: []
})

// 分页数据
const page = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 商品列表
const goodsList = ref([])
const selectedGoods = ref([])
const listView = ref('table')

// 批量操作按钮
const batchActions = [
  { label: '批量上架', value: GOODS_STATUS.ON_SALE, type: 'success' },
  { label: '批量下架', value: GOODS_STATUS.OFF_SALE, type: 'warning' },
  { label: '批量删除', value: 'delete', type: 'danger' }
]

// 快捷操作按钮
const quickActions = [
  { label: '商品分类', value: 'category', type: 'info', icon: 'Document' },
  { label: '规格模板', value: 'spec', type: 'warning', icon: 'Setting' },
  { label: '物流模板', value: 'logistics', type: 'success', icon: 'List' },
  { label: '数据统计', value: 'stats', type: 'primary', icon: 'TrendCharts' }
]

// 预览相关
const previewVisible = ref(false)
const previewTab = ref('detail')
const previewData = ref({})

// 导入相关
const importDialogVisible = ref(false)
const uploadHeaders = {
  // 设置上传请求头
}

// 获取统计数据
const fetchStats = async () => {
  loading.stats = true
  try {
    const { data } = await getGoodsStats()
    statsData.value = [
      {
        title: '商品总数',
        value: data.total,
        unit: '个',
        trend: data.totalTrend,
        tooltip: '店铺所有商品数量',
        type: 'primary'
      },
      {
        title: '在售商品',
        value: data.onSale,
        unit: '个',
        trend: data.onSaleTrend,
        tooltip: '当前在售商品数量',
        type: 'success'
      },
      {
        title: '本月销量',
        value: data.monthSales,
        unit: '件',
        trend: data.salesTrend,
        tooltip: '本月商品销售总量',
        type: 'warning'
      },
      {
        title: '本月销售额',
        value: data.monthAmount.toFixed(2),
        unit: '元',
        trend: data.amountTrend,
        tooltip: '本月商品销售总额',
        type: 'danger'
      }
    ]
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.stats = false
  }
}

// 获取商品列表
const fetchGoodsList = async () => {
  loading.list = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...filterForm,
      startTime: filterForm.dateRange?.[0],
      endTime: filterForm.dateRange?.[1]
    }
    const { data } = await getGoodsList(params)
    goodsList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.list = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchGoodsList()
}

// 重置
const handleReset = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'categoryIds' ? [] : ''
  })
  filterForm.dateRange = []
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGoodsList()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchGoodsList()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedGoods.value = selection
}

// 卡片选择
const handleCardSelect = (item, val) => {
  item.selected = val
  if (val) {
    selectedGoods.value.push(item)
  } else {
    const index = selectedGoods.value.findIndex(i => i.id === item.id)
    if (index > -1) {
      selectedGoods.value.splice(index, 1)
    }
  }
}

// 新建商品
const handleCreate = () => {
  // 跳转到商品创建页面
}

// 编辑商品
const handleEdit = (row) => {
  // 跳转到商品编辑页面
}

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await deleteGoods(row.id)
    ElMessage.success('删除成功')
    fetchGoodsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }
}

// 批量操作
const handleBatchAction = async (action) => {
  if (!selectedGoods.value.length) {
    return ElMessage.warning('请选择要操作的商品')
  }

  const ids = selectedGoods.value.map(item => item.id)
  try {
    if (action === 'delete') {
      await ElMessageBox.confirm('确定要删除选中的商品吗？', '提示', {
        type: 'warning'
      })
      await batchDeleteGoods(ids)
      ElMessage.success('批量删除成功')
    } else {
      await batchUpdateGoodsStatus(ids, action)
      ElMessage.success('批量操作成功')
    }
    fetchGoodsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量操作失败:', error)
      ElMessage.error('批量操作失败')
    }
  }
}

// 状态变更
const handleStatusChange = async (row, status) => {
  try {
    await updateGoodsStatus(row.id, status)
    ElMessage.success('操作成功')
    fetchGoodsList()
  } catch (error) {
    console.error('状态变更失败:', error)
    ElMessage.error('状态变更失败')
  }
}

// 卡片操作
const handleCardAction = (item, action) => {
  switch (action) {
    case 'on_sale':
      handleStatusChange(item, GOODS_STATUS.ON_SALE)
      break
    case 'off_sale':
      handleStatusChange(item, GOODS_STATUS.OFF_SALE)
      break
    case 'edit':
      handleEdit(item)
      break
    case 'delete':
      handleDelete(item)
      break
  }
}

// 商品预览
const handlePreview = async (row) => {
  previewVisible.value = true
  loading.preview = true
  try {
    const { data } = await getGoodsDetail(row.id)
    previewData.value = data
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.preview = false
  }
}

// 处理快捷操作
const handleQuickAction = (action) => {
  switch (action) {
    case 'category':
      // 跳转到商品分类页面
      break
    case 'spec':
      // 跳转到规格模板页面
      break
    case 'logistics':
      // 跳转到物流模板页面
      break
    case 'stats':
      // 跳转到数据统计页面
      break
  }
}

// 处理批量导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 下载导入模板
const downloadTemplate = () => {
  // 实现下载模板逻辑
}

// 上传前校验
const beforeImport = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                 file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件！')
    return false
  }
  return true
}

// 上传成功回调
const handleImportSuccess = (response) => {
  ElMessage.success('导入成功')
  importDialogVisible.value = false
  fetchGoodsList()
}

// 上传失败回调
const handleImportError = () => {
  ElMessage.error('导入失败')
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...filterForm,
      startTime: filterForm.dateRange?.[0],
      endTime: filterForm.dateRange?.[1]
    }
    const res = await exportGoods(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `商品数据_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 获取状态标签
const getStatusLabel = (status) => {
  return GOODS_STATUS[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    [GOODS_STATUS.DRAFT]: 'info',
    [GOODS_STATUS.PENDING]: 'warning',
    [GOODS_STATUS.APPROVED]: 'success',
    [GOODS_STATUS.REJECTED]: 'danger',
    [GOODS_STATUS.ON_SALE]: 'success',
    [GOODS_STATUS.OFF_SALE]: 'info',
    [GOODS_STATUS.SOLD_OUT]: 'warning',
    [GOODS_STATUS.DELETED]: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取商品类型标签
const getGoodsTypeLabel = (type) => {
  return GOODS_TYPE[type] || type
}

// 获取商品类型标签样式
const getGoodsTypeTag = (type) => {
  const typeMap = {
    [GOODS_TYPE.PHYSICAL]: 'primary',
    [GOODS_TYPE.VIRTUAL]: 'success',
    [GOODS_TYPE.SERVICE]: 'warning'
  }
  return typeMap[type] || 'info'
}

// 初始化趋势图表
const initTrendCharts = () => {
  trendChartRefs.value.forEach((el, index) => {
    if (!el) return
    
    const chart = echarts.init(el)
    const option = {
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      series: [{
        data: statsData.value[index].trendData,
        type: 'line',
        smooth: true,
        symbol: 'none',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: statsData.value[index].trend >= 0 ? '#67C23A' : '#F56C6C' },
            { offset: 1, color: 'rgba(255, 255, 255, 0.1)' }
          ])
        },
        lineStyle: {
          color: statsData.value[index].trend >= 0 ? '#67C23A' : '#F56C6C'
        }
      }]
    }
    chart.setOption(option)
  })
}

// 组件挂载时初始化
onMounted(() => {
  fetchStats()
  fetchGoodsList()
  nextTick(() => {
    initTrendCharts()
  })
})

// 组件卸载时销毁图表
onUnmounted(() => {
  trendChartRefs.value.forEach(chart => {
    chart && chart.dispose()
  })
})
</script>

<style scoped>
.goods-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.stats-card-title {
  font-size: 14px;
  color: #909399;
}

.stats-card-content {
  margin-bottom: 12px;
}

.stats-card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-card-unit {
  font-size: 14px;
  color: #909399;
  margin-left: 4px;
}

.stats-card-chart {
  margin-top: 12px;
}

.trend-chart {
  height: 50px;
}

.quick-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-card {
  margin-bottom: 20px;
}

.goods-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.goods-detail {
  flex: 1;
}

.goods-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.goods-sku {
  font-size: 12px;
  color: #909399;
}

.separator {
  margin: 0 8px;
  color: #DCDFE6;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.current-price {
  color: #F56C6C;
  font-weight: 500;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
  font-size: 12px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.goods-card {
  position: relative;
  transition: all 0.3s;
}

.goods-card:hover {
  transform: translateY(-4px);
}

.goods-card-header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: rgba(255, 255, 255, 0.9);
  z-index: 1;
}

.goods-card-content {
  cursor: pointer;
}

.goods-card-image {
  width: 100%;
  height: 280px;
  object-fit: cover;
}

.goods-card-info {
  padding: 12px;
}

.goods-card-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.goods-card-price {
  margin-bottom: 8px;
}

.goods-card-meta {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.goods-card-status {
  display: flex;
  justify-content: flex-end;
}

.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-content {
  padding: 20px;
}

.preview-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.preview-image {
  width: 300px;
  height: 300px;
  border-radius: 4px;
}

.preview-info {
  flex: 1;
}

.preview-title {
  margin: 0 0 12px;
  font-size: 20px;
}

.preview-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.preview-price {
  margin-bottom: 16px;
}

.preview-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .label {
    font-size: 12px;
    color: #909399;
  }
  
  .value {
    font-size: 20px;
  font-weight: 500;
    color: #303133;
  }
}

.preview-detail {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.review-list {
  .review-item {
    padding: 16px;
    border-bottom: 1px solid #EBEEF5;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .review-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
  }
  
  .review-user {
    flex: 1;
    
    .username {
      font-weight: 500;
    }
    
    .time {
      font-size: 12px;
      color: #909399;
    }
  }
  
  .review-content {
    margin-bottom: 12px;
    line-height: 1.6;
  }
  
  .review-images {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
    
    .review-image {
      width: 80px;
      height: 80px;
      border-radius: 4px;
    }
  }
  
  .review-reply {
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
    
    .reply-header {
      font-weight: 500;
      margin-bottom: 4px;
    }
    
    .reply-content {
      color: #606266;
    }
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  :deep(.el-upload-dragger) {
    width: 100%;
  }
  
  .el-upload__tip {
  margin-top: 12px;
    text-align: center;
  }
}

/* 响应式布局优化 */
@media screen and (max-width: 1400px) {
  .el-col-6 {
    width: 50%;
    margin-bottom: 20px;
  }
  
  .goods-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media screen and (max-width: 768px) {
  .el-col-6 {
    width: 100%;
  }
  
  .quick-actions {
    flex-direction: column;
    gap: 16px;
  }
  
  .goods-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
  
  .preview-header {
    flex-direction: column;
    
    .preview-image {
      width: 100%;
      height: auto;
    }
  }
}
</style>